import {createForm} from 'rc-form'
import {List, InputItem, Button, Toast, TextareaItem, ImagePicker, WhiteSpace, Picker} from 'antd-mobile'
import {history} from 'umi'
import React, {useEffect, useState} from 'react'
import {MyNavBar} from '@/components'
import {_getHouseMy, _postComment} from './store'

function CommentAdd(props) {
  const {getFieldProps, validateFields} = props.form

  const [ files, setFiles ] = useState([])

  const [ houseList, setHouseList ] = useState([])

  const handleChange = (files) => {
    if (files[0]?.file?.size / 1024 / 1024 > 5) {
      Toast.fail('图片大小不得超过5M')
      return
    }
    setFiles(files)
  }

  const initArea = async () => {
    const result = await _getHouseMy()
    if (result && result.length) {
      setHouseList(result.map(item => ({value: item.id, label: item.name})))
    }
  }

  useEffect(() => {
    initArea()
  }, [])

  const handleSubmit = () => {
    validateFields(async (err, val) => {
      if (err) {
        Toast.fail('请将信息补充完整')
        return
      }
      let pictures,
        houseId = undefined
      if (files && files.length) {
        pictures = files.map(item => item.url).join('|')
      }
      if (val.houseIds && val.houseIds.length) {
        houseId = +val.houseIds.join()
      }
      const result = await _postComment({
        ...val,
        pictures,
        houseId
      })
      if (result) {
        Toast.success('发布成功，请等待审核')
        history.push('/comment')
      }
    })
  }

  return (
    <div className='comment-add'>
      <MyNavBar title='发布论坛'/>
      <List>

        <InputItem
          {...getFieldProps('title', {
            rules: [ {required: true} ],
            initialValue: ''
          })}
          placeholder='标题'
        >
          标题：
        </InputItem>
        <TextareaItem
          title='内容'
          {...getFieldProps('content', {
            rules: [ {required: true} ],
            initialValue: ''
          })}
          rows={4}
          placeholder='内容'
        >
        </TextareaItem>
        <Picker data={houseList} cols={1} {...getFieldProps('houseIds')}>
          <List.Item arrow="horizontal">房屋</List.Item>
        </Picker>
        <List.Item>
          <ImagePicker files={files} selectable={files.length < 1} onChange={handleChange}/>
        </List.Item>
      </List>
      <WhiteSpace size='lg'/>
      <Button type='primary' onClick={handleSubmit}>发布</Button>
    </div>
  )
}

export default createForm()(CommentAdd)
